from playwright.sync_api import sync_playwright
from parsel import Selector


class Baidu:
    def search(self, keyword: str):
        ret = []
        with sync_playwright() as p:
            # 启动Chromium的轻量化配置
            browser = p.chromium.launch(
                headless=True,  # 新版无头模式（关键！资源占用大幅降低）
                args=["--no-sandbox"],
                slow_mo=100,  # 关闭延迟
            )
            context = browser.new_context(
                java_script_enabled=True,  # 仅保留必要JS
            )
            page = context.new_page()
            page.goto(
                "https://www.baidu.com/s?wd=%s&sa=fyb_n_homepage&rsv_dl=fyb_n_homepage&from=super&cl=3&tn=baidutop10&fr=top1000&rsv_idx=2&hisfilter=1"
                % keyword
            )
            text = page.content()
            selector = Selector(text=text)
            results = selector.css(".c-container.result")

            for result in results:
                title = "".join(result.css("h3 *::text").getall())
                url = result.css("h3 a::attr(href)").get()
                brief = "".join(result.css(".cos-row *::text").getall())
                ret.append({"title": title, "url": url, "brief": brief})
            browser.close()
            return ret


if __name__ == "__main__":
    baidu = Baidu()
    ret = baidu.search("武大")
    print(ret)
